package de.openlaboratory.elib.controller.servlets;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import de.openlaboratory.elib.core.LogManager;

public class BinaryServlet extends HttpServlet
{

	/**
	 * 
	 */
	private static final long serialVersionUID = -5942526089156187565L;

	private String fileType;
	private String fileIdentifier;

	private void processRequest(HttpServletRequest request, HttpServletResponse response)
	{
		getRequestedFileProperties(request);

		Path file = getFileFromRequest();

		if ("pdf".equals(this.fileType))
			sendFile(file, response);
		if ("img".equals(this.fileType))
			sendThumbnail(file, response);
	}

	private Path getFileFromRequest()
	{
		return Paths.get(fileIdentifier);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		processRequest(request, response);
	}

	private void getRequestedFileProperties(HttpServletRequest request)
	{
		String query = request.getQueryString();

		LogManager.logMessage("Binary file identifier: " + query);

		String[] args = query.split("&");

		if (args != null)
		{
			if (args.length > 0)
			{
				this.fileType = args[0];
			}

			if (args.length > 1)
			{
				//TODO: use URI class
				
				try
				{
					this.fileIdentifier = URLDecoder.decode(args[1], "UTF-8");
					LogManager.logMessage("Decoded file identifier: " + this.fileIdentifier);
				}
				catch (UnsupportedEncodingException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	private void sendFile(Path file, HttpServletResponse response)
	{
		int LENGTH_OF_FILE = (int) file.toFile().length();

		response.setContentType("application/pdf");
		response.setContentLength(LENGTH_OF_FILE);
		response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getFileName().toString() + "\"");
		try
		{
			File f = file.toFile();
			FileInputStream is = new FileInputStream(f);
			ServletOutputStream op = response.getOutputStream();
			
			byte[] outputByte=new byte[4096];

			int len;
			while(( len = is.read(outputByte, 0, 4096 )) > 0 ) {
			   op.write( outputByte, 0, len );
			}

            is.close();
            op.flush();
            op.close();
		}
		catch (IOException ioe)
		{
			ioe.printStackTrace();
		}
		catch (Exception p)
		{
			LogManager.logMessage("404..: " + p.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	private void sendThumbnail(Path file, HttpServletResponse response)
	{
		response.setContentType("image/jpg");
		
		try
		{
			// PdfReader pdfReader = new PdfReader(file.toAbsolutePath().toString());

			ServletOutputStream op = response.getOutputStream();

			PDDocument document = PDDocument.load(file.toAbsolutePath().toString());

			List<PDPage> pages = document.getDocumentCatalog().getAllPages();
			PDPage page = pages.get(0);

			BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 72);

			ImageIO.write(image, "jpg", op);
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception p)
		{
			LogManager.logMessage("There was a Unfall reading a thumbnail: " + p.getMessage());
		}
	}

}
